export default {
	namespaced: true,
	//模块数据
	state: () =>  ({
		/*
		购物车的数组，用来存储购物车中每个商品的信息对象，每个商品的信息对象，都包含如下6个属性：
		{ goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state}
		*/
		cart: JSON.parse( uni.getStorageSync('cart') || '[]'),
	}),
	
	mutations: {
		/**
		 * 根据提交的商品ID，查询购物车是否已存在该商品
		 * @param {*} state 
		 * @param {*} newGoods 加入购物车的商品信息
		**/
		addToCart(state, newGoods) {
			const resultFromCart = state.cart.find((oldGGoods) => oldGGoods.goods_id === newGoods.goods_id);
			if(!resultFromCart) {
				state.cart.push(newGoods);
			} else {
				resultFromCart.goods_count ++;	//诺有该商品，只更新数量即可
			}
			this.commit('my_cart/saveToStorage');
		},
		updateGoodsState(state, goods) {
			const findResult = state.cart.find((item) => item.goods_id === goods.goods_id);
			if(findResult) {
				findResult.goods_state = goods.goods_state;
				this.commit('my_cart/saveToStorage');
			}
		},
		updateGoodsCount(state, goods) {
			const findResult = state.cart.find((item) => item.goods_id === goods.goods_id);
			if(findResult) {
				findResult.goods_count = goods.goods_count;
				this.commit('my_cart/saveToStorage');
			}
		},
		removeGoodsById(state, goods_id) {
			state.cart = state.cart.filter((item) => item.goods_id !== goods_id);
			this.commit('my_cart/saveToStorage');
		},
		
		updateAllGoodsState(state, newState) {
			state.cart.forEach((item) => {
				item.goods_state = newState;
			});
			this.commit('my_cart/saveToStorage');
		},
		
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart));
		},
		
	},
	//store的计算属性
	getters: {
		//购物车商品的总量
		total(state) {
			let num = 0;
			state.cart.map((goods) => {
				num += goods.goods_count;
			});
			return num;
		},
		
		checkedCount(state) {
			return state.cart.filter((item) => item.goods_state).reduce((total, item2) => total += item2.goods_count, 0);
		},
		
			checkedGoodsAmount(state) {
			  // 先使用 filter 方法，从购物车中过滤器已勾选的商品
			  return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0).toFixed(2);
		},
	},
}